package com.ywy.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.ywy.common.rest.Result;
import com.ywy.shiro.AccountProfile;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 文件上传工具类
 *
 * @author ywy
 * @date 2021/12/27 16:56
 */
@Slf4j
@Component
public class UploadUtil {
    /**
     * 文件上传路径
     */
    public static String uploadDir;

    /**
     * 上传类型：头像
     */
    public static final String TYPE_AVATAR = "avatar";

    /**
     * 上传类型：文章
     */
    public static final String TYPE_POST = "post";

    @Value("${file.upload.dir}")
    public void setUploadDir(String uploadDir) {
        UploadUtil.uploadDir = uploadDir;
    }


    /**
     * 上传文件
     * @param type
     * @param file
     * @return
     */
    public Result upload(String type, MultipartFile file) {
        if (StringUtils.isBlank(type) || file.isEmpty()) {
            return Result.failure("上传失败");
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：{}", fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 文件上传路径
        String filePath = UploadUtil.uploadDir;
        if ("avatar".equalsIgnoreCase(type)) {
            AccountProfile profile = (AccountProfile) SecurityUtils.getSubject().getPrincipal();
            fileName = "/avatar/" + profile.getId() + suffixName;
        } else if ("post".equalsIgnoreCase(type)) {
            fileName = "/post/" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_FORMAT) + suffixName;
        }

        File dest = new File(filePath + fileName);
        // 判断是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("文件上传路径为：{}", filePath + fileName);
        String url = "/upload" + fileName;
        return Result.success(url);
    }
}
